#!/usr/bin/perl -w
use strict;

use Data::Dumper;
use Digest::MD5 qw(md5);
use File::Find;
use LWP::UserAgent;
use LWP::Simple;

my $userAgent = LWP::UserAgent->new;

find(\&findCallback, ".");

sub findCallback
{
# update files that look like OSM tiles
  updateTile($_, $File::Find::name) if( (-f $_) && $File::Find::name =~ m{/\d+/\d+/\d+\.png$} );
}

sub updateTile
{
  my ($localFilename, $fullFilename) = @_;
  $/ = undef;
  open TILE, $localFilename;
  my $oldTileData = <TILE>;
  close TILE;

  $fullFilename =~ m{(/\d+/\d+/\d+\.png$)};
  my $tileURL = "http://tile.openstreetmap.org$1";

# read the header, and convert the stored MD5 hash into binary
  my $header = $userAgent->head($tileURL);
  my $etag = $header->header("etag");
  $etag =~ s/\"//g;

# if the md5 hashes don't match, I need to update the tile
  if(md5($oldTileData) ne pack("H*", $etag))
  {
    print "Need to update $fullFilename. Downloading.\n";
    getstore($tileURL, $localFilename);
  }
  else
  {
    print "Do not need to update $fullFilename. Skipping.\n";
  }
}
